package cn.net.autocode.platform.table;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;


import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.dbManager.IdWorker;
import cn.net.autocode.core.bean.ResultT;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController("platformTableRules")
@RequestMapping("/platform/tableRules")
public class TableRules {
    private final Dao dictDao;

    public TableRules(@Qualifier("dictDao") Dao dictDao) {
        this.dictDao = dictDao;
    }

    @RequestMapping("load")
    public ResultT load(@RequestBody JSONObject param){
        JSONArray array = dictDao.queryJSONArray("select * from ac_table_rules where table_id=? order by rule_type,field_name",param.getString("tableId"));
        //字符串转jsonarray
        for(int i=0;i<array.size();i++){
            JSONObject json = array.getJSONObject(i);
            String refColumn = json.getString("refColumn");
            try {
                JSONArray refs = JSONArray.parseArray(refColumn);
                json.put("refColumn",refs);
            } catch (Exception e) {
                json.put("refColumn",new JSONArray());
            }
            json.put("keyWord",json.getString("fieldName"));
        }
        return ResultT.success(array);
    }

    @RequestMapping("addYsRule")
    public ResultT addYsRule(@RequestBody JSONObject param){
        param.put("id", IdWorker.ulid());
        dictDao.createJSON(param,"ac_table_rules");
        dictDao.executeUpdate("update ac_table set is_sync='N' where id=?",param.getString("tableId"));
        return ResultT.success(param);
    }

    @RequestMapping("/delete")
    public ResultT delete(@RequestBody JSONObject param){
        dictDao.executeUpdate("update ac_table set is_sync='N' where id in (select table_id from ac_table_rules where id=?)",param.getString("id"));
        dictDao.executeUpdate("delete from ac_table_rules where id=?",param.getString("id"));
        return ResultT.success();
    }
}
